

package com.maoshi.shop.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.app.dto.MyOrderDto;
import com.maoshi.shop.bean.app.dto.OrderItemDto;
import com.maoshi.shop.bean.app.dto.OrderShopDto;
import com.maoshi.shop.bean.app.dto.UserAddrDto;
import com.maoshi.shop.bean.enums.OrderStatus;
import com.maoshi.shop.bean.enums.RefundStatusEnum;
import com.maoshi.shop.bean.enums.RefundType;
import com.maoshi.shop.bean.model.*;
import com.maoshi.shop.common.bean.Qiniu;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.Arith;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/p/myOrder")
@Api(tags = "我的订单接口")
@AllArgsConstructor
public class MyOrderController {

    private final OrderService orderService;

    private final MapperFacade mapperFacade;

    private final UserAddrOrderService userAddrOrderService;

    private final ProductService productService;

    private final SkuService skuService;
    private final Qiniu qiniu;

    private final MyOrderService myOrderService;

    private final ShopDetailService shopDetailService;

    private final OrderItemService orderItemService;

    private final OrderRefundService orderRefundService;


    /**
     * 订单详情信息接口
     */
    @GetMapping("/orderDetail")
    @ApiOperation(value = "订单详情信息", notes = "根据订单号获取订单详情信息")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<OrderShopDto> orderDetail(@RequestParam(value = "orderNumber", required = true) String orderNumber) {

        String userId = SecurityUtils.getUser().getUserId();
//        String userId = "1";
        OrderShopDto orderShopDto = new OrderShopDto();

        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);
        ShopDetail shopDetail;
        if(Objects.equals(order.getShopId(),Constant.PLATFORM_SHOP_ID)){
            shopDetail = new ShopDetail();
            shopDetail.setShopName(Constant.PLATFORM_SHOP_NAME);
        }else {
            shopDetail = shopDetailService.getShopDetailByShopId(order.getShopId());
        }
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());

        UserAddrDto userAddrDto = mapperFacade.map(userAddrOrder, UserAddrDto.class);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);


        List<OrderItemDto> orderItemDtoList = mapperFacade.mapAsList(orderItems, OrderItemDto.class);
        orderShopDto.setShopId(shopDetail.getShopId());
        orderShopDto.setShopName(shopDetail.getShopName());
        orderShopDto.setActualTotal(order.getActualTotal());
        orderShopDto.setUserAddrDto(userAddrDto);

        orderShopDto.setTransfee(order.getFreightAmount());
//        Math.abs
        orderShopDto.setReduceAmount( Math.abs(order.getReduceAmount()));
        orderShopDto.setCreateTime(order.getCreateTime());
        orderShopDto.setRemarks(order.getRemarks());
        orderShopDto.setOrderType(order.getOrderType());
        orderShopDto.setStatus(order.getStatus());
        // 付款时间
        orderShopDto.setPayTime(order.getPayTime());
        // 发货时间
        orderShopDto.setDvyTime(order.getDvyTime());
        // 完成时间
        orderShopDto.setFianllyTime(order.getFinallyTime());
        // 取消时间
        orderShopDto.setCancelTime(order.getCancelTime());
        // 更新时间
        orderShopDto.setUpdateTime(order.getUpdateTime());




        List<OrderRefund> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());

        // 可以退款的状态，并在退款时间内
        if (order.getStatus() > OrderStatus.UNPAY.value() && order.getStatus() < OrderStatus.CLOSE.value() && orderRefundService.checkRefundDate(order) ) {
            orderShopDto.setCanRefund(true);
            // 有没有正在退款中的订单
            if (CollectionUtil.isEmpty(orderRefunds)) {
                orderShopDto.setCanAllRefund(true);
            }
        }

        for (OrderRefund orderRefund : orderRefunds) {

            // 整单退款
            if (Objects.equals(RefundType.ALL.value(),orderRefund.getRefundType())) {
                orderShopDto.setCanRefund(false);
                // 统一的退款单号
                for (OrderItemDto orderItemDto : orderItemDtoList) {
                    orderItemDto.setRefundSn(orderRefund.getRefundSn());
                }
                break;
            }
            // 单项退款，每个单号都不一样
            for (OrderItemDto orderItemDto : orderItemDtoList) {
                if (Objects.equals(orderItemDto.getOrderItemId(), orderRefund.getOrderItemId())) {
                    orderItemDto.setRefundSn(orderRefund.getRefundSn());
                }
            }

        }

        orderShopDto.setOrderItemDtos(orderItemDtoList);
        double total = 0.0;
        Integer totalNum = 0;
        for (OrderItemDto orderItem : orderShopDto.getOrderItemDtos()) {
            total = Arith.add(total, orderItem.getProductTotalAmount());
            totalNum += orderItem.getProdCount();
        }
        orderShopDto.setTotal(total);
        orderShopDto.setTotalNum(totalNum);

        //合并代码开始
        orderShopDto.setOrderTypeBasket(order.getOrderTypeBasket());
        //合并代码结束

        return ResponseEntity.ok(orderShopDto);
    }


    /**
     * 订单列表接口
     */
    @GetMapping("/myOrder")
    @ApiOperation(value = "订单列表信息", notes = "根据订单状态获取订单列表信息，状态为0时获取所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败", required = false, dataType = "Integer"),
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrder(@RequestParam(value = "status") Integer status,PageParam<MyOrderDto> page) {

        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByUserIdAndStatus(page, userId, status,null);
        return ResponseEntity.ok(myOrderDtoIpage);
    }

    /**
     * 获取订单项信息
     */
    @GetMapping("/getOrderItem")
    public ResponseEntity<OrderItem> getOrderItem(@RequestParam(value = "orderItemId") Long orderItemId) {
        OrderItem orderItem = orderItemService.getById(orderItemId);
        orderItem.setPic(orderItem.getPic() !=null ?qiniu.getResourcesUrl() + orderItem.getPic() :null);
        return ResponseEntity.ok(orderItem);
    }

    /**
     * 订单评价列表接口
     */
    @GetMapping("/myOrderComment")
    @ApiOperation(value = "订单评价列表接口", notes = "根据订单评价状态获取订单列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commStatus", value = "订单状态 0:待评价 1已评价", required = false, dataType = "Integer")
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrderComment(@RequestParam(value = "commStatus") Integer commStatus,PageParam<MyOrderDto> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByUserIdAndStatus(page, userId, 0,commStatus);
        return ResponseEntity.ok(myOrderDtoIpage);
    }

    /**
     * 订单列表查询接口
     */
    @GetMapping("/myOrderSearch")
    @ApiOperation(value = "订单列表信息查询", notes = "根据订单编号或者订单中商品名称搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "orderName",value = "订单编号或者订单中商品名称", required = false,dataType = "String"),
            @ApiImplicitParam(name = "orderTimeStatus",value = "0全部订单 1最近七天 2最近三个月 3三个月之前 订单", required = false,dataType = "Integer"),
            @ApiImplicitParam(name = "orderType",value = "0全部订单 1拼团订单 2秒杀订单 3普通订单", required = false,dataType = "Integer")
    })
    public ResponseEntity<IPage<MyOrderDto>> myOrderSearch(@RequestParam(value = "status") Integer status,
                                                           @RequestParam(value = "orderName") String orderName,
                                                           @RequestParam(value = "orderTimeStatus") Integer orderTimeStatus,
                                                           @RequestParam(value = "orderType") Integer orderType,
                                                           PageParam<MyOrderDto> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<MyOrderDto> myOrderDtoIpage = myOrderService.pageMyOrderByParams(page, userId, status,orderName,orderTimeStatus,orderType);
        return ResponseEntity.ok(myOrderDtoIpage);
    }


    /**
     * 取消订单
     */
    @PutMapping("/cancel/{orderNumber}")
    @ApiOperation(value = "根据订单号取消订单", notes = "根据订单号取消订单")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<String> cancel(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();
        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);
        if (!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value())) {
            throw new MaoshiShopBindException("订单已支付，无法取消订单");
        }

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        order.setOrderItems(orderItems);
        // 取消订单
        orderService.cancelOrders(Collections.singletonList(order));
        // 清除缓存
        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
        }
        return ResponseEntity.ok().build();
    }


    /**
     * 确认收货
     */
    @PutMapping("/receipt/{orderNumber}")
    @ApiOperation(value = "根据订单号确认收货", notes = "根据订单号确认收货")
    public ResponseEntity<String> receipt(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();
        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);

        if (!Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value())) {
            throw new MaoshiShopBindException("订单未发货，无法确认收货");
        }
        if (Objects.equals(order.getRefundStatus(), RefundStatusEnum.APPLY.value())) {
            throw new MaoshiShopBindException("订单退款中，无法确认收货");
        }
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        order.setOrderItems(orderItems);
        // 确认收货
        orderService.receiptOrder(Collections.singletonList(order));

        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderNumber}")
    @ApiOperation(value = "根据订单号删除订单", notes = "根据订单号删除订单")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<String> delete(@PathVariable("orderNumber") String orderNumber) {
        String userId = SecurityUtils.getUser().getUserId();

        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);

        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value()) ) {
            throw new MaoshiShopBindException("订单未完成或未关闭，无法删除订单");
        }

        // 删除订单
        orderService.deleteOrders(Collections.singletonList(order));

        return ResponseEntity.ok("删除成功");
    }




//    /**
//     * 获取我的订单订单数量
//     */
//    @GetMapping("/orderCount")
//    @ApiOperation(value = "获取我的订单订单数量", notes = "获取我的订单订单数量")
//    public ResponseEntity<OrderCountData> getOrderCount() {
//        String userId = SecurityUtils.getUser().getUserId();
//        OrderCountData orderCountMap = orderService.getOrderCount(userId);
//        return ResponseEntity.ok(orderCountMap);
//    }


}
